<template>
  <el-dialog
    v-model="visible"
    title="创建用户"
    width="500px"
    @close="resetForm"
  >
    <el-form ref="userFormRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          type="password"
          show-password
        />
      </el-form-item>

      <el-form-item label="初始积分" prop="initialPoints">
        <el-input-number v-model="form.initialPoints" />
      </el-form-item>

      <el-form-item label="是否启用" prop="enabled">
        <el-switch v-model="form.enabled" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          placeholder="请输入备注"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确认</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { createUser } from "@/api/userApi";
// import { register } from "@/api/authApi";
import { message } from "@/utils/message";

interface UserForm {
  username: string;
  password: string;
  initialPoints: number;
  enabled: boolean;
  remark: string;
}

const visible = ref(false);

const form = reactive<UserForm>({
  username: "",
  password: "",
  initialPoints: 0,
  enabled: true,
  remark: ""
});

const emits = defineEmits(["refresh"]);

const rules: FormRules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, message: "用户名至少3个字符", trigger: "blur" }
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码至少6个字符", trigger: "blur" }
  ],
  initialPoints: [
    {
      type: "number",
      required: true,
      message: "请输入正确的数字",
      trigger: "blur"
    },
    {
      pattern: /^[-+]?(\d+(\.\d+)?|\.\d+)$/,
      message: "请输入正确的数字",
      trigger: "blur"
    }
  ]
};

const userFormRef = ref<FormInstance>();

const submitForm = () => {
  userFormRef.value?.validate(async valid => {
    if (valid) {
      try {
        await createUser(form);
        message("创建成功", { type: "success" });
        visible.value = false;
        emits("refresh");
      } catch (error) {
        console.error(error);
      }
    }
  });
};

const resetForm = () => {
  userFormRef.value?.resetFields();
};

const open = () => {
  visible.value = true;
};

defineExpose({ open });
</script>
